<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/12/7
 * Time: 9:42
 */

namespace api\storage\model;


use think\Model;

class BomDetailModel extends Model
{
    protected $table = 'iwh_bom_detail';
    protected $pk = 'uuid';


    /**
     * 根据条件查询bom单详情的欠料信息
     *
     * @param array $where
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryBomDetailLackMaterial($where = [])
    {
        return $this->alias('a')
            ->join(['iwh_supplier_materiel' => 'b'], 'a.sub_materiel_id=b.sub_materiel_id', 'left')
            ->where($where)
            ->field('b.sub_materiel_id,ABS(b.count) as count')
            ->select();
    }

    /**
     * 根据条件查询bom单相关的厂商库存信息
     *
     * @param array $where
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function querySupplierMaterielWithBom($where = [])
    {
        return $this->alias('a')
            ->join(['iwh_supplier_materiel' => 'b'], 'a.sub_materiel_id=b.sub_materiel_id', 'inner')
            ->join(['iwh_sub_materiel' => 'c'], 'a.sub_materiel_id=c.sub_materiel_id', 'left')
            ->where($where)
            ->field('b.sub_materiel_id,b.count,c.shelves_type as type,c.min_quantity')
            ->order('b.sub_materiel_id')
            ->select();
    }

    /**
     * 根据uuid查询bom_detail信息
     *
     * @param $uuid
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryBomByUuid($uuid)
    {
        return $this->where('bom_uuid', $uuid)->field('sub_materiel_id,count,uuid')->select();
    }

    public function queryLocalLackMateriel($bomUuid)
    {
        $where['bom_uuid'] = $bomUuid;
        $where['flag'] = ['lt', 0];
        return $this->where($where)->field("sub_materiel_id,ABS(flag) as count,count as ocount,uuid")->select();
    }

    /**
     * 批量添加数据
     *
     * @param $data
     * @return array|false
     * @throws \Exception
     */
    public function addAll($data)
    {
        return $this->saveAll($data);
    }

    public function updateDetail($bomUuid, $materielId, $data)
    {
        $detailWhere['bom_uuid'] = $bomUuid;
        $detailWhere['sub_materiel_id'] = $materielId;
        return $this->isUpdate(true)->save($data, $detailWhere);
    }

    public function updateCleanCount($bomUuid)
    {
        $where['bom_uuid'] = $bomUuid;
        $where['flag'] = ['lt', 0];
        return $this->isUpdate(true)->save(['flag' => 0], $where);
    }
}